<template>
  <a-tooltip
    v-if="isShowTooltip"
    placement="topLeft"
    trigger="hover"
    :mouse-leave-delay="0"
  >
    <template #title>
      <span>{{ contentText }}</span>
    </template>
    <div ref="contentParent" class="content">
      <span ref="content">
        <slot></slot>
      </span>
    </div>
  </a-tooltip>
  <div v-else ref="contentParent" class="content">
    <span ref="content">
      <slot></slot>
    </span>
  </div>
</template>
<script lang="ts">
import { Prop, Vue, Component, Watch } from 'vue-property-decorator'

@Component({
  components: {},
})
export default class ToolTip extends Vue {
  @Prop({ type: [String, Number], default: '' }) private content!:
    | string
    | number
  @Prop({ type: [Number], default: 80 }) private width!: number
  @Prop({ type: [Number], default: 80 }) private unitWidth!: number // 拖拽表格右下角也会改变unitWidth

  public isShowTooltip: boolean = false

  public get isShow() {
    return this.isShowTooltip
  }

  public get contentText() {
    return this.content
  }

  /**
   * 重新计算是否需要展示tooltip
   * 1、检测列宽度的变化时，这里特指用户手动拖动改变某一列的宽度
   * 2、翻页时，检测内容的改变
   * 3、拖拽表格右下角改变表格宽度时，这里通过检测unitWidth来实现
   */
  @Watch('width', { immediate: true })
  private watchWidth() {
    this.computeFun()
  }

  @Watch('content', { immediate: true })
  private watchContent() {
    this.computeFun()
  }

  @Watch('unitWidth', { immediate: true })
  private watchIsDragged() {
    this.computeFun()
  }

  public computeIsShowToolTip() {
    this.$nextTick(() => {
      const $content = this.$refs.content as HTMLElement
      const $contentParent = this.$refs.contentParent as HTMLElement
      const contentWidth = $content?.offsetWidth
      const contentParentWidth = $contentParent?.offsetWidth
      if (contentParentWidth > contentWidth) {
        this.isShowTooltip = false
      } else {
        this.isShowTooltip = true
      }
    })
  }

  public computeFun() {
    // 确保渲染之后获取到单元格的宽度
    setTimeout(() => {
      this.computeIsShowToolTip()
    }, 10)
  }

  private mounted() {
    this.computeFun()
  }
}
</script>
<style scoped>
.content {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
